<template>
  <div class="">
    <Filterelement
      WhichPage="其他费用"
      @searchBtn="searchBtn"
      @reset="reset"
      @handleExport="handleExport"
      @ToLeadInto="ToLeadInto"
      @handleSign="handleSign"
      @handleAdd="handleAdd"
      :Params="Params"
      @downloadX="downloadX"
      :gangwei="gangwei"
      :yewu="yewu"
      @submitShenHe="submitShenHe"
      @revocationShenHe="revocationShenHe"
      :userList="configList"
    />

    <div
      style="
        background-color: #fff;
        margin: 10px 20px 20px;
        padding: 16px;
        position: relative;
      "
    >
      <div class="tableHeader">
        <div class="line"></div>
        <div class="tableHeaderText">其他费用管理</div>
      </div>

      <el-table
        v-loading="loading"
        :data="configList"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ color: '#fff' }"
        height="310"
      >
        <el-table-column type="selection" width="55" align="center" fixed />
        <el-table-column label="序号" type="index" width="50" fixed />
        <el-table-column
          label="月份"
          align="center"
          prop="happenMonth"
          width="80"
          fixed
        >
        </el-table-column>
        <el-table-column
          label="费用名称"
          align="center"
          prop="title"
          width="160"
          fixed
        >
          <template #default="scope">
            <span>{{ scope.row.actualTime }}{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="金额"
          align="center"
          prop="amount"
          width="100"
        />
        <el-table-column
          label="税率(%)"
          align="center"
          prop="taxRate"
          width="75"
        />
        <el-table-column
          label="含税额"
          align="center"
          prop="taxIncluded"
          width="100"
        />
        <el-table-column
          label="附件"
          align="center"
          prop="fileName"
          width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span
              style="color: #4781be"
              v-for="(item, index) in scope.row.fileDtos"
              :key="index"
              >{{ item.fileName }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="费用发生时间"
          align="center"
          prop="createTime"
          width="180"
        />
        <el-table-column
          label="审核状态"
          align="center"
          prop="auditStatus"
          width="100"
        >
          <template #default="scope">
            <!-- 1：待提交 2：待审核 3：审核中 4审核通过 5：审核不通过 #CC3339-->
            <!-- :style="{
                color:
                  scope.row.auditStatus == 3 || scope.row.auditStatus == 4
                    ? '#3175BE'
                    : scope.row.auditStatus == 5
                    ? '#CC3339'
                    : '',
              }" -->
            <span>{{
              scope.row.auditStatus == 1
                ? "待提交"
                : scope.row.auditStatus == 2
                ? "待审核"
                : scope.row.auditStatus == 3
                ? "审核中"
                : scope.row.auditStatus == 4
                ? "审核通过"
                : "审核不通过"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="left"
          width="430"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-space>
              <div class="linkBtn" @click="handleFowlPath(scope.row)">
                查看流程节点
              </div>
              <el-button
                color="#3175BE"
                @click="handleUpdate(scope.row)"
                v-if="
                  (scope.row.auditStatus == 1 || scope.row.auditStatus == 5) &&
                  INdex
                "
                >编辑</el-button
              >
              <el-button
                color="#3175BE"
                @click="examin(scope.row)"
                v-if="
                  (scope.row.auditStatus == 1 || scope.row.auditStatus == 5) &&
                  INdex
                "
                >提交审核</el-button
              >
              <el-button color="#3175BE" @click="fileDown(scope.row)"
                >下载附件</el-button
              >

              <el-popconfirm
                title="确认删除该数据么?"
                @confirm="delBtn(scope.row)"
                width="180"
                v-if="
                  (scope.row.auditStatus == 1 || scope.row.auditStatus == 5) &&
                  INdex
                "
              >
                <template #reference>
                  <div class="delBtn">删除</div>
                </template>
              </el-popconfirm>
              <el-button
                v-if="
                  roleName?.indexOf(scope.row.roleName) === 0 &&
                  (scope.row.auditStatus === 2 || scope.row.auditStatus === 3)
                "
                color="#3175BE"
                @click="handleSign(scope.row)"
                >会签</el-button
              >
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="Params.pageNum"
        v-model:limit="Params.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      destroy-on-close
      @close="formDialogClose"
    >
      <el-form
        ref="configRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="费用发生月份" prop="happenMonth">
          <el-date-picker
            v-model="form.happenMonth"
            value-format="YYYY-MM"
            type="month"
            placeholder="请选择"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="费用名称" prop="actualTime">
          <el-col :span="10">
            <el-date-picker
              v-model="form.actualTime"
              value-format="YYYY-MM"
              type="month"
              placeholder="请选择"
              clearable
              style="width: 100%"
            ></el-date-picker>
          </el-col>
          <el-col :span="14">
            <el-select v-model="form.title" placeholder="请选择" clearable>
              <el-option
                v-for="item in nameData"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            /></el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input
            v-model="form.amount"
            @input="amountInput"
            placeholder="请输入"
          >
            <template #suffix> ￥ </template>
          </el-input>
        </el-form-item>
        <el-form-item label="税率(%)" prop="taxRate">
          <el-input
            v-model="form.taxRate"
            @input="taxRateInput"
            placeholder="请输入"
          >
            <template #suffix> % </template>
          </el-input>
        </el-form-item>
        <el-form-item label="含税额" prop="taxIncluded">
          <el-input disabled v-model="form.taxIncluded">
            <template #suffix> ￥ </template>
          </el-input>
        </el-form-item>
        <!-- prop="fileUrl" -->
        <el-form-item label="附件">
          <el-upload
            v-model:file-list="file"
            :headers="headers"
            class="upload-demo"
            :action="uploadFileUrl"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :data="{ filePath: '/other/' }"
          >
            <el-button type="primary" color="#3175BE">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">(支持上传xlsx、jpg等格式)</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" color="#3175BE" @click="submitForm"
            >确 认</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 流程弹窗 -->
    <FlowPath
      :dialogVisible="dialogVisible"
      @dialogClose="dialogClose"
      :title="dialogTitle"
      :businessId="businessId"
    ></FlowPath>
    <!-- 会签弹窗 -->
    <Countersign
      :dialogSign="dialogSign"
      @dialogSignClose="dialogSignClose"
      :title="dialogSignTitle"
      :Judgewhattosign="'其他费用'"
      :ID="submitTjID"
    ></Countersign>
  </div>
</template>

<script setup >
import Filterelement from "../zujian/filterelement";
import {
  otherList, //列表
  save, //新增
  submitAudit, //审核提交
  withdrawAudit, //审核撤回
  deleteOth, //删除
  update, //修改
  otherExport, //导出
  upload, //上传
  dict,
} from "@/api/otherCosts/index";
import download from "../../../plugins/download.js";
import { ref, onMounted, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import JSZip from "jszip";
import FileSaver from "file-saver";
const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_yes_no } = proxy.useDict("sys_yes_no");
// 获取传入信息
const urlParams = new URLSearchParams(window.location.search);
// const id = urlParams.get("id");
const userName = urlParams.get("userName");
const roleName = urlParams.get("roleName");
const INdex = ref(false);
const headers = {
  userName: encodeURIComponent(userName),
  roleName: encodeURIComponent(roleName),
};
// const shuzu = ['人力资源','项目经理','小微主','财务','财务部长']
if (roleName?.indexOf("人力资源") == 0) {
  INdex.value = true;
  if (router.currentRoute.value.query?.qw === "1") {
    INdex.value = true;
  }
} else {
  INdex.value = false;
  if (router.currentRoute.value.query?.qw === "1") {
    INdex.value = true;
  } else {
    INdex.value = false;
  }
}

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const configList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(2);
const title = ref("");
const dateRange = ref([]);
const fileTypeData = ref([
  // 1：待提交 2：待审核 3：审核中 4审核通过 5：审核不通过
  {
    value: "1",
    label: "待提交",
  },
  {
    value: "2",
    label: "待审核",
  },
  {
    value: "3",
    label: "审核中",
  },
  {
    value: "4",
    label: "审核通过",
  },
  {
    value: "5",
    label: "审核不通过",
  },
]);
const nameData = ref([]);
const data = reactive({
  form: {
    happenMonth: "",
    amount: "",
    actualTime: "",
    title: "",
    file: [],
    taxIncluded: "",
    taxRate: "",
    id: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    auditStatus: undefined,
    endTime: undefined,
    startTime: undefined,
    title: undefined,
  },
  Params: {
    pageNum: 1,
    // pageNum1: 1,
    pageSize: 10,
    // pageSize1: 10,
    endTime: "", //结束时间
    startTime: "", //	开始时间
    auditStatus: "", //		审核状态(1:待提交，2：待审核，3：审核中，4：通过，5：不通过)
    title: "",
  },
  rules: {
    happenMonth: [{ required: true, message: "请选择", trigger: "blur" }],
    title: [{ required: true, message: "请输入", trigger: "blur" }],
    amount: [{ required: true, message: "请输入", trigger: "blur" }],
    actualTime: [{ required: true, message: "请选择", trigger: "blur" }],
    taxRate: [{ required: true, message: "请输入", trigger: "blur" }],
    file: [{ required: true, message: "请上传", trigger: "blur" }],
  },
  file: [],
});
onMounted(() => {
  if (router.currentRoute.value.query.id) {
    console.log(router.currentRoute.value.query.id);
    dialogSign.value = true;
    submitTjID.value = router.currentRoute.value.query.id;
  }
});
const fileList = ref([]);
// 流程弹窗
const dialogVisible = ref(false);
const dialogTitle = ref("");
const businessId = ref(null);
// 会签弹窗
const dialogSign = ref(false);
const dialogSignTitle = ref("");

//提交审核id
const submitTjID = ref();
const submitTjStatus = ref(false);
const { queryParams, form, rules, Params, file } = toRefs(data);

/** 查询参数列表 */
function getList() {
  loading.value = true;
  otherList(data.Params).then((response) => {
    console.log("response--", response);
    configList.value = response.data.items;
    total.value = response.data.total;
    loading.value = false;
    submitTjID.value = null;
  });
}
// 费用名称字典
function getDict() {
  dict("pm_other_cost_type").then((res) => {
    nameData.value = res.data;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 重置 */
function reset(moneyDate) {
  if (!moneyDate.value[0]) {
    data.Params.startTime = "";
    data.Params.endTime = "";
  }
  data.Params = {
    endTime: "", //结束时间
    startTime: "", //	开始时间
    auditStatus: "", //		审核状态(1:待提交，2：待审核，3：审核中，4：通过，5：不通过)
    title: "", //			姓名
  };
  getList();
  // proxy.resetForm("configRef");
}
/** 搜索按钮操作 */
const searchBtn = (moneyDate) => {
  console.log("moneyDate", moneyDate);
  data.Params.pageNum = 1;
  if (moneyDate.value) {
    data.Params.startTime = moneyDate.value[0];
    data.Params.endTime = moneyDate.value[1];
  } else {
    data.Params.startTime = "";
    data.Params.endTime = "";
  }
  console.log("搜索", data.Params);
  getList();
};
// function handleQuery() {
//   queryParams.value.pageNum = 1;
//   getList();
// }
/** 重置按钮操作 */
// function resetQuery() {
//   dateRange.value = [];
//   proxy.resetForm("queryRef");
//   handleQuery();
// }
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  console.log(selection);
  if (selection.length !== 0) {
    submitTjID.value = selection[0]?.id;
    ids.value = selection.map((item) => item.configId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  } else {
    submitTjID.value = null;
    submitTjStatus.value = false;
  }
}

/** 导出按钮操作 */
function handleExport() {
  otherExport(data.Params).then((res) => {
    console.log(res, "cccccccccccccccccccccccc");
    var elink = document.createElement("a");
    var name = "其他费用管理";
    elink.download = name;
    elink.style.display = "none";
    var blob = new Blob([res], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
  });
  // proxy.download(
  //   "system/config/export",
  //   {
  //     ...queryParams.value,
  //   },
  //   `config_${new Date().getTime()}.xlsx`
  // );
}
/** 新增按钮操作 */
function handleAdd() {
  // reset();
  open.value = true;
  title.value = "新建其他费用内容";
}
// 含税额计算
function amountInput() {
  console.log(1 + data.form.taxRate / 100);
  if (data.form.amount && data.form.taxRate) {
    data.form.taxIncluded = data.form.amount * (1 + data.form.taxRate / 100);
  } else {
    data.form.taxIncluded = "";
  }
}
function taxRateInput() {
  console.log(1 + data.form.taxRate / 100);
  if (data.form.amount && data.form.taxRate) {
    data.form.taxIncluded = data.form.amount * (1 + data.form.taxRate / 100);
  } else {
    data.form.taxIncluded = "";
  }
}
// 表格文件下载
// function getImgArrayBuffer(url) {
//   return new Promise((resolve, reject) => {
//     //通过请求获取文件blob格式
//     let xmlhttp = new XMLHttpRequest();
//     xmlhttp.open("GET", url, true);
//     xmlhttp.responseType = "blob";
//     xmlhttp.onload = function () {
//       if (this.status == 200) {
//         resolve(this.response);
//       } else {
//         reject(this.status);
//       }
//     };
//     xmlhttp.send();
//   });
// }
function fileDown(row) {
  row.fileDtos.map((item) => {
    download.saveAs(item.fileUrl, item.fileName);
  });

  // ElMessage({
  //   message: "该功能暂未开放",
  //   grouping: true,
  //   type: "warning",
  // });
  // todo
}
/** 修改按钮操作 */
function handleUpdate(row) {
  // reset();
  //   const configId = row.configId || ids.value;
  //   getConfig(configId).then((response) => {
  // form.value = response.data;
  console.log("hhhhh", row);
  open.value = true;
  title.value = "修改其他费用内容";
  data.form.amount = row.amount;
  data.form.actualTime = row.actualTime;
  data.form.title = row.title;
  data.file = [];
  data.form.file = [];
  row.fileDtos.forEach((item) => {
    data.form.file.push({
      name: item.fileName,
      url: item.fileUrl,
    });
    data.file.push({
      name: item.fileName,
      url: item.fileUrl,
    });
  });

  data.form.happenMonth = row.happenMonth;
  data.form.taxIncluded = row.taxIncluded;
  data.form.taxRate = row.taxRate;
  data.form.id = row.id;

  //   });
}
// 表格提交审核
function examin(row) {
  submitAudit(row.id).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: res.msg,
        grouping: true,
        type: "success",
      });
      getList();
    } else {
      ElMessage({
        message: res.msg,
        grouping: true,
        type: "error",
      });
    }
  });
}
// 表格删除
function delBtn(row) {
  console.log(row);
  deleteOth(row.id).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: res.msg,
        grouping: true,
        type: "success",
      });
      getList();
    } else {
      ElMessage({
        message: res.msg,
        grouping: true,
        type: "error",
      });
    }
  });
}
/** 附件上传 */
const handleChange = (uploadFile, uploadFiles) => {
  // fileList.value = fileList.value.slice(-3);
};
const handleSuccess = (uploadFile, uploadFiles) => {
  console.log("uploadFile", uploadFile, uploadFiles, data.file);
  // if (uploadFile) {
  //   data.file.push({
  //     name: uploadFiles.name,
  //     url: uploadFiles.response.data,
  //   });
  // }
};

/** 提交按钮 */
function submitForm() {
  // console.log(data.form.id, form.value.id);
  proxy.$refs["configRef"].validate((valid) => {
    if (valid) {
      data.form.file = [];
      data.form.file = data.form.file.concat(
        data.file.map((item) => ({
          fileName: item.name,
          fileUrl: item.response.data,
        }))
      );
      console.log(data.form);
      if (form.value.id) {
        // var formobj = {
        //   form.value
        // }
        update(form.value.id, form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        save(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 新增 编辑弹窗关闭
function formDialogClose() {
  data.form.amount = "";
  data.form.actualTime = "";
  data.form.title = "";
  data.form.file = [];
  data.form.happenMonth = "";
  data.form.taxIncluded = "";
  data.form.taxRate = "";
  data.form.id = "";
}
/** 流程 */
const handleFowlPath = (row) => {
  dialogVisible.value = true;
  dialogTitle.value = "其他成本会签流程节点";
  businessId.value = row.id;
};
const dialogClose = () => {
  dialogVisible.value = false;
  businessId.value = null;
};

/** 会签 */
const handleSign = (row) => {
  console.log(row.auditStatus, "22222222222");
  submitTjID.value = row.id;
  dialogSign.value = true;
};
const dialogSignClose = () => {
  dialogSign.value = false;
  getList();
};
//导入弹窗
const ToLeadInto = () => {
  open.value = true;
};
//提交审核
const submitShenHe = () => {
  // var params = {
  //     id: submitTjID.value,
  // };
  if (submitTjID.value) {
    submitAudit(submitTjID.value).then((res) => {
      console.log(res, "11111111111111111111");
      if (res.code == 200) {
        ElMessage({
          message: res.msg,
          grouping: true,
          type: "success",
        });
        getList();
      } else {
        ElMessage({
          message: res.msg,
          grouping: true,
          type: "error",
        });
      }
    });
  } else {
    ElMessage({
      message: "请先选择一条数据",
      grouping: true,
      type: "warning",
    });
  }
};
//撤回审核
const revocationShenHe = () => {
  // var params = {
  //   id: submitTjID.value,
  // };
  if (submitTjID.value) {
    withdrawAudit(submitTjID.value).then((res) => {
      if (res.code == 200) {
        ElMessage({
          message: res.msg,
          grouping: true,
          type: "success",
        });
        getList();
      } else {
        ElMessage({
          message: res.msg,
          grouping: true,
          type: "error",
        });
      }
    });
  } else {
    ElMessage({
      message: "请先选择一条数据",
      grouping: true,
      type: "warning",
    });
  }
};
getList();
getDict();
</script>
<style lang='scss'  scoped>
.formBox {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 16px;
}
.tableHeader {
  width: 100%;
  font-size: 20px;
  height: 35px;
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  .line {
    width: 4px;
    height: 18px;
    background-color: #2e70b6;
    margin-right: 4px;
  }
  .tableHeaderText {
    font-size: 18px;
    font-weight: 500;
  }
}
.linkBtn {
  width: 100px;
  cursor: pointer;
  color: #3175be;
  text-decoration: underline;
}
.delBtn {
  cursor: pointer;
  color: #cc3339;
}
</style>
